<template>
  <div class="register">
    <van-nav-bar
      title="用户注册"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="register-panel"/>
    <van-field
      v-model="userName"
      label="用户名"
      placeholder="请输入用户名"
      required
      :error-message="userNameErrorMsg"
    />
    <van-field
      v-model="password"
      required
      placeholder="请输入密码"
      type="password"
      label="密码"
      :error-message="passwordErrorMsg"
    />
    <div class="register-button">
      <van-button
        type="primary"
        size="large"
        @click="handleRegister"
        :loading="registerLoading"
      >
        马上注册
      </van-button>
    </div>
  </div>
</template>

<script>
  import axios from 'axios';
  import md5 from 'md5';
  // Toast提示不需要使用use()加载
  import { Toast } from "vant";
  import requestUrl from '../../serverApi';

  export default {
    data() {
      return {
        userName: '',
        password: '',
        registerLoading: false,
        userNameErrorMsg: '',
        passwordErrorMsg: '',
      }
    },
    methods: {
      goBack() {
        this.$router.go(-1);
      },
      handleRegister() {
        // 注册用户操作
        this.checkForm() && this.registerUser();
      },
      registerUser() {
        // 注册用户请求
        this.registerLoading = true;
        axios.post(requestUrl.registerUser, {
          userName: this.userName,
          password: md5(this.password),
        }, {
          withCredentials: true,
        }).then((res) => {
          if (res.data.code === 200) {
            Toast.success(res.data.message);
            // 保存登录状态
            localStorage.userInfo = JSON.stringify({ userName: this.userName });
            this.$router.push('/'); // 暂时先跳转到首页
          } else {
            Toast.fail('注册失败');
            this.registerLoading = false;
          }
        }).catch((err) => {
          Toast.fail('注册失败');
          this.registerLoading = false;
        })
      },
      checkForm() {
        // 校验提交表单
        let isOk = true;
        if (this.userName.length < 2) {
          this.userNameErrorMsg = '用户名长度不得少于2位';
          isOk = false;
        } else {
          this.userNameErrorMsg = '';
        }
        if (this.password.length < 6) {
          this.passwordErrorMsg = '密码长度不得少于6位';
          isOk = false;
        } else {
          this.passwordErrorMsg = '';
        }
        return isOk;
      }
    }
  }
</script>

<style scoped>
  .register {
    background: #fff;
  }
  .register-panel{
    width:96%;
    border-radius: 5px;
    padding-bottom:50px;
  }
  .register-button{
    padding-top:10px;
  }
</style>